import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Jiange
 * @create 2021-07-16-13:18
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //一共有三个资源
        Semaphore semaphore = new Semaphore(3);

        for ( int i = 0; i < 6; i++) {
            new Thread(()->{
                try{
                    semaphore.acquire();//获取资源
                    System.out.println(Thread.currentThread().getName()+"----抢到车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName()+"----离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();//释放资源
                }
            },String.valueOf(i)).start();
        }
    }
}
